# -*- coding: utf-8 -*-
# @Time    : 2021/10/26 17:50
# @Author  : super
import socket
import threading
import fromework


class HttpServer(object):

	def __init__(self):
		# 创建socket链接
		tcp_socket_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

		# 设置端口号服用
		tcp_socket_server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)

		# 指定地址、端口
		tcp_socket_server.bind(("", 9091))

		# 创建链接请求数
		tcp_socket_server.listen(128)

		#初始化socket
		self.tcp_socket_server = tcp_socket_server


	def response(self, file_data, new_socket_client) :
		# 响应行
		response_lines = "HTTP/1.1 200 OK\r\n"
		# 响应头
		response_header = "Server: BWS/1.0 www.baidu.com\r\n"
		# 响应体
		response_body = file_data

		# 封装到一起
		response = (response_lines + response_header + "\r\n").encode("gbk") + response_body
		new_socket_client.send(response)

	def headding_requests(self, new_socket_client) :
		# 客户端给服务端发送数据
		recv = new_socket_client.recv(4096)
		if len(recv) == 0 :
			print("客户关闭了浏览器....")
			new_socket_client.close()
			return

		path_name = recv.decode("gbk").split(" ", 2)

		if path_name[1] == "/" :
			path_name[1] = "/index.html"

		print(path_name[1])

		if path_name[1].endswith(".html"):
			# 动态资源请求
			env = {
				"request_path" : path_name[1]
			}
			status, headers, data = fromework.handle_request(env)
			# 响应行
			response_lines = "HTTP/1.1 %s\r\n" %status
			# 响应头
			response_header = ""
			# 遍历头部信息
			for header in headers :
				# 拼接多个响应头
				response_header += "%s: %s\r\n" % header
			# 响应体
			response_body = data

			# 封装到一起
			response_data = (response_lines +
			                 response_header +
			                 "\r\n" +
			                 response_body).encode("utf-8")
			new_socket_client.send(response_data)
			new_socket_client.close()
		else:
			# 静态资源请求
			try :
				# 给客户端发送数据
				with open("../static" + path_name[1], "rb") as file :
					file_data = file.read()

				self.response(file_data, new_socket_client)

			except Exception as e :
				# 给客户端发送数据
				with open("../static/error.html", "rb") as file :
					file_data = file.read()
				self.response(file_data, new_socket_client)

			finally :
				# 关闭客户端链接
				new_socket_client.close()

	def main(self) :

		while True :
			# 等待客户建立链接
			new_socket_client, ip_ropt = self.tcp_socket_server.accept()
			# 当客户端和服务器建立连接程，创建子线程
			sub_thread = threading.Thread(target = self.headding_requests, args = (new_socket_client,))
			# 设置守护主线程
			sub_thread.setDaemon(True)
			# 启动子线程执行对应的任务
			sub_thread.start()

if __name__ == '__main__':
	tcp_client_socket = HttpServer()
	tcp_client_socket.main()
